﻿using FrameworkCore.Constants;
using FrameworkCore.Extensions;

namespace Microsoft.Extensions.Configuration;

/// <summary>
/// 配置文件扩展类
/// </summary>
public static class ConfigurationsExtensions
{
    /// <summary>
    /// 获取全局的配置文件
    /// </summary>
    /// <param name="builder"></param>
    /// <param name="fileName">配置文件名；默认获取（appsettings.json）</param>
    /// <returns></returns>
    public static IConfiguration GetGlobalConfigurations(this IConfigurationBuilder builder, string fileName = "appsettings.json")
    {
        return builder
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile(fileName, optional: true, reloadOnChange: true)
            .Build();
    }

    /// <summary>
    /// 获取全局的配置
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="key">键值</param>
    /// <param name="fileName">文件名</param>
    /// <returns></returns>
    public static T GetGlobalSection<T>(string key, string fileName = "appsettings.json")
    {
        return new ConfigurationBuilder().GetGlobalConfigurations(fileName).GetSection(key).Get<T>()!;
    }

    /// <summary>
    /// 获取全局的数据库连接配置
    /// </summary>
    /// <param name="key">键值</param>
    /// <returns></returns>
    public static string GetConnectionString(string key)
    {
        return new ConfigurationBuilder().GetGlobalConfigurations().GetConnectionString(key)!;
    }

    /// <summary>
    /// 获取模块的配置
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="key">键值</param>
    /// <param name="fileName">文件名</param>
    /// <returns></returns>
    public static T GetModulesSection<T>(string key, string fileName)
    {
      return  AddJsonFile(fileName).GetSection(fileName).GetValue<T>(key)!;
    }

    /// <summary>
    /// 获取自定义配置文件
    /// </summary>
    /// <param name="fileName">配置文件名称</param>
    /// <param name="paths">配置文件路径</param>
    /// <returns></returns>
    public static IConfigurationRoot AddJsonFile(string fileName, List<string>? paths = null)
    {
        if (paths == null)
        {
            paths = GetGlobalSection<List<string>>(GlobalConstants.ModulePathsKey);
        }

        var jsonFilePath = Path.Combine(ApplicationPartManagerExtensions.GetModulesDirectory(paths), $"{fileName.Replace(".json", "")}.json");

        return new ConfigurationBuilder().AddJsonFile(jsonFilePath, false, true).Build();
    }
}

